package com.epfuse.cloud.gateway.config;

import com.epfuse.cloud.gateway.filter.EpfuseRequestGlobalFilter;
import com.epfuse.cloud.gateway.filter.PasswordDecoderFilter;
import com.epfuse.cloud.gateway.filter.SwaggerBasicGatewayFilter;
import com.epfuse.cloud.gateway.filter.ValidateCodeGatewayFilter;
import com.epfuse.cloud.gateway.handler.GlobalExceptionHandler;
import com.epfuse.cloud.gateway.handler.ImageCodeHandler;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @Author : 孙峰
 * @Description: 网关配置
 * @Date : 2022/7/18  21:24
 *
 * proxyBeanMethods = true 或不写，是Full模式
 *
 * Full模式下通过方法调用指向的仍旧是原来的Bean
 *
 * proxyBeanMethods = false 是lite模式
 *
 * Spring Boot在2.2.0版本（依赖于Spring 5.2.0）起就把它的所有的自动配置类的此属性改为了false，即@Configuration(proxyBeanMethods = false)，提高Spring启动速度
 *
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(GatewayConfigProperties.class)
public class GatewayConfiguration {

    @Bean
    public PasswordDecoderFilter passwordDecoderFilter(GatewayConfigProperties configProperties) {
        return new PasswordDecoderFilter(configProperties);
    }

    /**
     * 注册全局过滤器
     * @return
     */
    @Bean
    public EpfuseRequestGlobalFilter epfuseRequestGlobalFilter() {
        return new EpfuseRequestGlobalFilter();
    }

    @Bean
    @ConditionalOnProperty(name = "swagger.basic.enabled")
    public SwaggerBasicGatewayFilter swaggerBasicGatewayFilter(
            SpringDocConfiguration.SwaggerDocProperties swaggerProperties) {
        return new SwaggerBasicGatewayFilter(swaggerProperties);
    }

    @Bean
    public ValidateCodeGatewayFilter validateCodeGatewayFilter(GatewayConfigProperties configProperties,
                                                               ObjectMapper objectMapper, RedisTemplate<String, Object> redisTemplate) {
        return new ValidateCodeGatewayFilter(configProperties, objectMapper, redisTemplate);
    }

    @Bean
    public GlobalExceptionHandler globalExceptionHandler(ObjectMapper objectMapper) {
        return new GlobalExceptionHandler(objectMapper);
    }

    @Bean
    public ImageCodeHandler imageCodeHandler(RedisTemplate<String, Object> redisTemplate) {
        return new ImageCodeHandler(redisTemplate);
    }

}
